<!--
 选择区域
-->
<template>
  <div class="flow-select-tree-box">
    <div class="search-box">
      <a-input-search v-model:value="searchText" allow-clear placeholder="请输入姓名或拼音或登录名检索" @search="onSearch" />
    </div>
    <div class="select-role-box">
      <!--多选-->
      <a-tree
        :ref="treeRefName"
        v-model:checkedKeys="treeCheckedKeys"
        v-model:selectedKeys="treeCheckedKeys"
        v-model:expandedKeys="expandedKeys"
        :height="260"
        :multiple="treeCheckable"
        :checkable="treeCheckable"
        :load-data="loadDataAsyn"
        :tree-data="treeData"
        :loading="loading"
        :show-line="true && { showLeafIcon: false }"
        :show-icon="false"
        :loaded-keys="treeLoadedKeys"
        @select="selectTree"
        @check="checkTree"
        @load="onLoad"
      >
        <template v-slot:title="{ title, attributes, deptName }">
          <!-- 选人组件图标 -->
          <span class="user-icon">
            <avic-icon v-if="attributes && attributes.nodeType == 'user'" svg="avic-account-circle-fill" color="#3370ff" />
            <avic-icon v-else-if="attributes && attributes.nodeType == 'dept'" svg="avic-organization-chart" color="#0035cc" />
            <avic-icon v-else-if="selectTag == 'role'" svg="avic-account-box-fill" color="#0035cc" />
            <avic-icon v-else-if="selectTag == 'group'" svg="avic-team-fill" color="#0035cc" />
            <avic-icon v-else-if="selectTag == 'position' && !isExpand" svg="avic-folder-2-fill" color="#0035cc" />
            <avic-icon v-else-if="selectTag == 'position' && isExpand" svg="avic-folder-open-fill" color="#0035cc" />
            <avic-icon v-else svg="avic-building-fill" color="#0035cc" />
          </span>
          <a-tooltip placement="topLeft" :mouse-enter-delay="1">
            <template v-slot:title>
              <!-- 显示名称 -->
              <span v-if="searchText && title.indexOf(searchText) > -1">
                {{ title.substr(0, title.indexOf(searchText)) }}
                <span style="color: #f50">{{ searchText }}</span>
                {{ title.substr(title.indexOf(searchText) + searchText.length) }}
              </span>
              <span v-else>
                {{ title }}
              </span>
              <!-- 显示全路径 -->
              <span
                v-if="showMoreUserInfo.length > 0 && attributes && attributes[showMoreUserInfo[0]] != null && selectTag !== 'orgDept'"
                class="cell-txt-dept"
              >
                (
                <span v-for="(infoItem, index) in showMoreUserInfo" :key="infoItem">
                  {{ attributes[infoItem] }}
                  <span v-if="index < showMoreUserInfo.length - 1">,</span>
                </span>
                )
              </span>
              <span v-else-if="deptName && deptName != null" class="cell-txt-dept">（{{ deptName }}）</span>
              <span v-else-if="attributes && attributes['deptName'] != null" class="cell-txt-dept">（{{ attributes['deptName'] }}）</span>
            </template>
            <!-- 显示名称 -->
            <span v-if="searchText && title.indexOf(searchText) > -1">
              {{ title.substr(0, title.indexOf(searchText)) }}
              <span style="color: #f50">{{ searchText }}</span>
              {{ title.substr(title.indexOf(searchText) + searchText.length) }}
            </span>
            <span v-else>
              {{ title }}
            </span>
            <!-- 显示全路径 -->
            <span
              v-if="attributes && showMoreUserInfo.length > 0 && attributes[showMoreUserInfo[0]] != null && selectTag !== 'orgDept'"
              class="cell-txt-dept"
            >
              (
              <span v-for="(infoItem, index) in showMoreUserInfo" :key="infoItem">
                {{ attributes[infoItem] }}
                <span v-if="index < showMoreUserInfo.length - 1">,</span>
              </span>
              )
            </span>
            <span v-else-if="deptName && deptName != null" class="cell-txt-dept">（{{ deptName }}）</span>
            <span v-else-if="attributes && attributes['deptName'] != null" class="cell-txt-dept">（{{ attributes['deptName'] }}）</span>
          </a-tooltip>
        </template>
      </a-tree>
    </div>
  </div>
</template>
<!-- eslint-disable max-lines -->
<script>
import { setUserList, processNodes } from './_util';
import request from '@/utils/request';

export default {
  name: 'SelectTree',
  props: {
    type: {
      type: String,
      required: true,
      default: 'orgDept'
    },
    // prop接收传过来的参数
    select: {
      type: Object,
      required: true // 校验
    },
    data: {
      type: Object,
      required: true, // 校验
      default: null
    },
    selectAll: {
      type: String,
      required: false, // 校验
      default: ''
    },
    formId: {
      type: String,
      required: false, // 校验
      default: ''
    },
    visible: {
      type: Boolean,
      required: false,
      default: false
    },
    buttonData: {
      required: false,
      type: Object,
      default: null
    },
    // 流程实例
    bpmInstanceObject: {
      type: Object,
      default: null
    },
    defaultSelectedUser: {
      type: Array,
      required: true,
      default: () => []
    },
    showMoreUserInfo: {
      type: Array,
      default: () => []
    },
    // check时选中孙子节点,打开时会层层异步加载子节点的子节点，关闭时只加载一层子节点
    checkChildrenNode: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  data() {
    return {
      selectUser: [], // 选中的用户
      noChange: false,
      searchList: [],
      userList: [],
      treeCheckedKeys: [],
      treeSelectedKeys: [],
      expandedKeys: [],
      treeData: [],
      defaultMaxParentId: '-1',
      initTreeData: [], // 初始化加载树数据
      tableRefName: 'userListTable',
      treeRefName: 'avicTreeElement',
      deptUrl: '/bpm/bpmActor/bpmSelectUserAction2/dept/v1', // 部门树访问地址
      positionUrl: '/bpm/bpmActor/bpmSelectUserAction2/position/v1', // 岗位树访问地址
      groupUrl: '/bpm/bpmActor/bpmSelectUserAction2/group/v1', // 群组树访问地址
      roleUrl: '/bpm/bpmActor/bpmSelectUserAction2/role/v1', // 角色树访问地址
      selectFlowTab: 0, // 当前选中的流程页签
      selectTag: '', // 当前选人的纬度类型
      // 树组件需要的加载数据格式
      treeParam: {
        url: '',
        parameter: {
          checked: false
        },
        method: 'post'
      },
      // 树搜索组件需要的加载数据格式
      searchTreeParam: {
        url: '/bpm/bpmActor/bpmSelectUserAction2/getSearchUsersJSONData/v1',
        parameter: {},
        method: 'post'
      },
      isSwitch: false,
      showSearchList: false,
      searchText: '',
      treeCheckable: true, // 是否多选
      scopedSlots: { title: 'title' }, // 树收藏
      menuList: [],
      menuVisible: false,
      addCommonContactUrl: '/bpm/bpmActor/bpmSelectUserAction2/addCommonContact/v1',
      delCommonContactUrl: '/bpm/bpmActor/bpmSelectUserAction2/delCommonContact/v1',
      rightNode: null,
      roleSpinning: false,
      treeNodeDataRef: {}, // 当前节点信息
      loading: false, // bigtree loading
      selectListMap: {}, // bigtree 选中的用户
      expandLevel: '1', // 展开层级
      emptyText: '暂无数据', // 搜索为空时的提示数据
      treeLoadedKeys: [],
      needCheckedKeys: [] // 需要选中的节点记录
    };
  },
  /** 参数 select {selectFlowTab:3 当前激活的分支节点页签, selectTag:"user" 节点可选择的维度} */
  watch: {
    select: {
      immediate: true,
      handler(newV) {
        // 判断是否跟传入的维度type是否一致，不一致则不执行操作
        if (newV.selectTag && this.type && newV.selectTag !== this.type) {
          return;
        }
        if (
          newV &&
          newV.selectTag &&
          newV.selectFlowTab > -1 &&
          (newV.selectTag !== this.selectTag || newV.selectFlowTab !== this.selectFlowTab)
        ) {
          this.selectFlowTab = newV.selectFlowTab; // 记录当前激活的分支页签
          if (newV.selectTag !== this.selectTag) {
            this.isSwitch = true; // 标记为新切换的 选人维度
          }
          this.showSearchList = false;
          this.searchText = '';
          this.selectTag = newV.selectTag; // 记录当前 选人维度
          this.iniTree();
          this.setDefaultSelectUser(this.defaultSelectedUser);
        }
      }
    }
  },
  mounted() {
    // this.iniTree();
  },
  methods: {
    /** 初始化树列表 */
    iniTree() {
      if (this.loading) {
        return;
      }
      if (this.selectTag && this.selectFlowTab > -1) {
        this.iniTreeUrl(); // 初始化请求参数
        this.iniTreeData(); // 初始化数据
      }
    },
    /** 1.初始化查询路径url */
    iniTreeUrl() {
      if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].currentActivityAttr) {
        if (
          this.data.nextTask[this.selectFlowTab].currentActivityAttr.dealType === '1' ||
          this.data.nextTask[this.selectFlowTab].currentActivityAttr.single === 'yes'
        ) {
          // 单选用户
          this.treeCheckable = false;
        } else {
          this.treeCheckable = true;
        }
      }
      if (this.selectTag !== 'user') {
        const para = [];
        let list = '';
        let nodeType = '';
        if (this.selectTag === 'orgDept') {
          if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].orgList.length > 0) {
            list = 'orgList'; // 组织
            nodeType = 'rootOrg';
          } else if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].deptList.length > 0) {
            list = 'deptList'; // 部门
            nodeType = 'root';
          }
          this.treeParam.url = this.data.orgDeptTreeUrl ? this.data.orgDeptTreeUrl : this.deptUrl;
        } else if (this.selectTag === 'role') {
          list = 'roleList';
          nodeType = this.selectTag;
          this.treeParam.url = this.data.roleTreeUrl ? this.data.roleTreeUrl : this.roleUrl;
        } else if (this.selectTag === 'group') {
          list = 'groupList';
          nodeType = this.selectTag;
          this.treeParam.url = this.data.groupTreeUrl ? this.data.groupTreeUrl : this.groupUrl;
        } else if (this.selectTag === 'position') {
          list = 'positionList';
          nodeType = this.selectTag;
          this.treeParam.url = this.data.positionTreeUrl ? this.data.positionTreeUrl : this.positionUrl;
        }
        if (
          this.data.nextTask &&
          list !== '' &&
          this.data.nextTask[this.selectFlowTab][list] &&
          this.data.nextTask[this.selectFlowTab][list].length > 0
        ) {
          this.data.nextTask[this.selectFlowTab][list].forEach((tim) => {
            para.push(tim.id);
          });
        }
        const buttonData = this.getButtonData();
        if (this.selectTag === 'role') {
          this.setParameter(para, buttonData);
        } else {
          this.treeParam.parameter = {
            nodeType,
            para: JSON.stringify(para),
            filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '',
            secretLevel: this.data.secretLevel,
            formId: this.formId,
            executionId: buttonData.buttonData.executionId,
            processInstanceId: buttonData.buttonData.processInstanceId,
            taskId: buttonData.buttonData.taskId
          };
        }
      }
    },
    /*
        获取流程参数
    */
    getButtonData() {
      if (this.visible) {
        return { buttonData: this.buttonData, submitFuncName: '' };
      }
      return this.bpmInstanceObject.bpmCommonSelect;
    },
    /*
        2. bigtree 初始化数据
    */
    async iniTreeData() {
      this.initTreeData = [];
      this.expandedKeys = [];
      this.treeLoadedKeys = [];
      let treeData = [];

      if (this.selectTag === 'orgDept') {
        if (this.data.orgDeptTreeZNode && this.data.orgDeptTreeZNode.length > 0) {
          treeData = this.data.orgDeptTreeZNode;
        }
      } else if (this.selectTag === 'role') {
        if (this.data.currentActivityAttr?.cfSelectUser === 'true') {
          // 成飞复杂角色树
          this.$emit('loading', true);

          const result = await this.getRole();
          if (result.success) {
            treeData = result.result;
            this.processInitRole(treeData);
          }
          this.$emit('loading', false);
        } else {
          // 平台正常角色树
          if (this.data.roleTreeZNode && this.data.roleTreeZNode.length > 0) {
            treeData = this.data.roleTreeZNode;
          } else {
            if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].roleList.length > 0) {
              treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].roleList);
            }
          }
        }
      } else if (this.selectTag === 'user') {
        if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].userList.length > 0) {
          treeData = setUserList(this.data.nextTask[this.selectFlowTab].userList, this.treeCheckable);
        }
      } else if (this.selectTag === 'model') {
        if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].modelList.length > 0) {
          treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].modelList);
        }
      } else if (this.selectTag === 'group') {
        if (this.data.groupTreeZNode && this.data.groupTreeZNode.length > 0) {
          treeData = this.data.groupTreeZNode;
        } else {
          if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].groupList.length > 0) {
            treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].groupList);
          }
        }
      } else if (this.selectTag === 'position') {
        if (this.data.positionTreeZNode && this.data.positionTreeZNode.length > 0) {
          treeData = this.data.positionTreeZNode;
        } else {
          if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].positionList.length > 0) {
            treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].positionList);
          }
        }
      }

      // tree 中放入数据
      if (this.selectTag !== 'orgDept' && this.selectTag !== 'root') {
        this.expandLevel = '2';
        // this.treeData = [...treeData];
        this.setExpandedKeys(treeData); // 初始化展开节点
      } else if (this.selectTag === 'orgDept') {
        this.expandLevel = '2';
        this.autoLoadAsyn();
      }
    },
    /**
        3.数据加载前参数设置
     */
    beforeLoadData(treeData, parentId) {
      if (treeData.attributes && treeData.attributes.nodeType) {
        this.treeParam.parameter.nodeType = treeData.attributes.nodeType;
      }
      this.treeParam.parameter.formId = '';
      this.treeParam.parameter.id = parentId;
      this.treeNodeDataRef = treeData;
    },
    /**
     *  4. 数据加载完成事件
     */
    afterLoadData(res) {
      if (this.treeCheckable) {
        if (res.data.length > 0) {
          // this.setTreeData(res.data,this.treeNodeDataRef.key);
        }
      }
      if (res.data.length === 0) {
        this.treeNodeDataRef.disableCheckbox = true;
        this.treeNodeDataRef.disabled = true;
        this.treeNodeDataRef.isLeaf = true;
      }
    },
    /**
     * 设置参数---CF流程自定义选人方案
     */
    setParameter(para, buttonData) {
      if (this.data.currentActivityAttr?.cfSelectUser === 'true') {
        // CF复杂角色树
        let toActivityName = '';
        if (this.buttonData && this.buttonData.targetActivityName) {
          toActivityName = this.buttonData.targetActivityName;
        } else if (this.data.nextTask.length > 0) {
          toActivityName = this.data.nextTask[0].currentActivityAttr.activityName;
        }
        let deptImpl = '';
        if (this.data.nextTask.length > 0 && this.data.nextTask[0].currentActivityAttr.deptImpl) {
          deptImpl = this.data.nextTask[0].currentActivityAttr.deptImpl;
        }
        this.treeParam.parameter = {
          nodeType: '',
          para: '',
          roleIds: para.join(','),
          procInstId: buttonData.buttonData.processInstanceId,
          fromActivityName: this.data.currentActivityAttr.activityName ? this.data.currentActivityAttr.activityName : '',
          toActivityName,
          deptImpl,
          processKey: this.data.processKey ? this.data.processKey : '',
          filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '',
          secretLevel: this.data.secretLevel,
          formId: this.data.formId,
          executionId: buttonData.buttonData.executionId,
          taskId: buttonData.buttonData.taskId,
          id: ''
        };
      } else {
        // 平台正常角色树
        this.treeParam.parameter = {
          nodeType: 'role',
          id: buttonData.buttonData.id,
          para: JSON.stringify(para),
          filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '',
          secretLevel: this.data.secretLevel,
          formId: this.data.formId,
          checked: ''
        };
      }
    },
    /**
     * 异步获取角色树---成飞流程自定义选人方案
     */
    async getRole() {
      this.roleSpinning = true;
      const result = await request({
        url: this.roleUrl,
        data: this.treeParam.parameter,
        method: 'post'
      });
      return new Promise((resolve) => {
        this.roleSpinning = false;
        if (result.success) {
          resolve(result);
        } else {
          resolve(result);
        }
      });
    },
    /**
     * 角色节点处理 -- 成飞选人
     */
    processInitRole(tree) {
      if (tree && tree.length > 0) {
        tree.forEach((tim) => {
          if (tim.attributes.nodeType !== 'user') {
            tim.isLeaf = false;
            tim.disableCheckbox = false;
          }
          if (tim.children) {
            this.processInitRole(tim.children);
          }
        });
      }
    },
    /**
     * 搜索 1.点击搜索
     */
    onSearch(e) {
      if (e) {
        this.showSearchList = true;
        const searchCondition = this.getSearchCondition();
        let { selectTag } = this;
        if (selectTag === 'user') {
          selectTag = 'userList';
        }
        let paramDeptIds = '';
        if (this.selectTag === 'role') {
          if (this.initTreeData && this.initTreeData.length > 0) {
            if (this.initTreeData[0].attributes.nodeType === 'dept') {
              paramDeptIds = this.initTreeData[0].attributes.deptId;
            }
          }
        }
        const parameter = {
          searchContent: e,
          searchType: selectTag,
          searchCondition,
          paramDeptIds,
          secretLevel: this.data.secretLevel,
          filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || ''
        };
        this.$emit('loading', true);
        request({
          url: this.searchTreeParam.url,
          data: parameter,
          method: this.searchTreeParam.method
        })
          .then((res) => {
            if (res.success) {
              if (res.data && res.data.length > 0) {
                this.setSearchList(res.data);
                this.treeData = [...this.searchList];
              } else {
                if (parameter.searchContent !== '') {
                  this.$message.warning(res.errorDesc || '未查询到匹配数据！');
                } else {
                  this.$message.warning('暂无数据！');
                }
              }
            } else {
              this.showSearchList = false;
            }
            this.$emit('loading', false);
          })
          .catch(() => {
            this.showSearchList = false;
            this.$emit('loading', false);
          });
      } else {
        this.showSearchList = false;
        this.iniTreeData();
      }
    },
    /**
     * 搜索 step 2.拼接查询条件
     */
    getSearchCondition() {
      let conditionList = [];
      let nextTask = null;
      if (this.data.nextTask.length >= this.selectFlowTab) {
        nextTask = this.data.nextTask[this.selectFlowTab];
      }
      if (nextTask) {
        if (this.selectTag === 'user') {
          const condition = {};
          condition.processInstanceId = nextTask.currentActivityAttr.processInstanceId;
          condition.executionId = nextTask.currentActivityAttr.executionId;
          if (nextTask.currentActivityAttr.outcome == null || nextTask.currentActivityAttr.outcome === 'null') {
            condition.outcome = '';
          } else {
            condition.outcome = nextTask.currentActivityAttr.outcome;
          }

          condition.type = nextTask.currentActivityAttr.type;
          condition.targetActivityName = nextTask.currentActivityAttr.targetActivityName;
          condition.userId = nextTask.currentActivityAttr.userId;
          condition.taskId = nextTask.currentActivityAttr.taskId;
          condition.index = nextTask.currentActivityAttr.index;
          conditionList[0] = condition;
        } else if (this.selectTag === 'orgDept') {
          if (nextTask.orgList != null && nextTask.orgList.length && nextTask.orgList.length > 0) {
            for (let i = 0; i < nextTask.orgList.length; i++) {
              const orgInfo = {};
              orgInfo.id = nextTask.orgList[i].id;
              orgInfo.name = nextTask.orgList[i].name;
              orgInfo.type = 'org';
              conditionList.push(orgInfo);
            }
          } else {
            for (let i = 0; i < nextTask.deptList.length; i++) {
              const deptInfo = {};
              deptInfo.id = nextTask.deptList[i].id;
              deptInfo.name = nextTask.deptList[i].name;
              deptInfo.type = 'dept';
              conditionList.push(deptInfo);
            }
          }
        } else if (this.selectTag === 'role') {
          conditionList = nextTask.roleList;
        } else if (this.selectTag === 'model') {
          conditionList = nextTask.modelList;
        } else if (this.selectTag === 'group') {
          conditionList = nextTask.groupList;
        } else if (this.selectTag === 'position') {
          conditionList = nextTask.positionList;
        }
        // if(conditionList.length>0){
        //   conditionList[0].secretLevel = '3'
        // }
      }

      return JSON.stringify(conditionList);
    },
    /**
     * 搜索 step 3.缓存符合查询条件的数据
     */
    setSearchList(list) {
      this.searchList = [];
      if (list && list.length > 0) {
        list.forEach((user) => {
          this.searchList.push({
            key: user.id || user.userId,
            attributes: {
              deptId: user.deptId,
              deptName: user.deptName,
              deptNamePath: user.deptNamePath,
              nodeType: 'user'
            },
            isLeaf: true,
            title: user.userName,
            deptId: user.deptId,
            deptName: user.deptName,
            id: user.id || user.userId,
            name: user.userName,
            orderBy: user.orderBy
          });
        });
      }
    },
    /**
     * 切换选人事件 （父组件调用此方法回显已选人员）
     */
    changeSelectUser(list) {
      this.noChange = true;
      this.setDefaultSelectUser(list);
    },
    /**
     * 切换选人时 设置默认选中的user
     */
    setDefaultSelectUser(list) {
      if (list && list.length > 0) {
        let checkedKeys = [];
        this.selectListMap = {};
        list.forEach((tim) => {
          if (tim.selectFlowTab === this.selectFlowTab) {
            if (tim.users.length === 0) {
              checkedKeys = [];
            } else {
              tim.users.forEach((user) => {
                // checkedKeys.push(user.key);
                this.selectListMap[user.id + user.attributes.deptId] = user; // 初始化listmap
              });
            }
          }
        });
        // this.treeCheckedKeys = checkedKeys;
        this.selectUser = [...list];
        // if (checkedKeys.length > 0) {
        //   this.dealTreeCheckedKeys(this.treeData, checkedKeys);
        //   this.treeCheckedKeys = [...checkedKeys];
        // }
        // #42335 【VUE3.0】【流程设计-减签】：减签页面删除已选用户后，待选用户的复选框没有取消选中
        this.dealTreeCheckedKeys(this.treeData, checkedKeys);

        this.treeCheckedKeys = [...checkedKeys];
      }
    },
    dealTreeCheckedKeys(treeData, checkedKeys) {
      treeData.forEach((item) => {
        Object.keys(this.selectListMap).forEach((key) => {
          if (this.selectListMap[key].id === item.id && item.attributes.deptId === this.selectListMap[key].attributes.deptId) {
            this.selectListMap[key] = item;
            if (!checkedKeys.includes(item.key)) {
              checkedKeys.push(item.key);
            }
          }
        });
        // const itemkeyLength = item.key.length <= 32 ? item.key.length : item.key.length - 32;
        // if (!checkedKeys.includes(item.key)) {
        //   checkedKeys.forEach((tim, index) => {
        //     const timKeyLength = tim.length <= 32 ? tim.length : tim.length - 32;
        //     if (
        //       tim.substring(0, timKeyLength) &&
        //       item.key.substring(0, itemkeyLength) &&
        //       tim.substring(0, timKeyLength) === item.key.substring(0, itemkeyLength)
        //     ) {
        //       // 添加到checkedKeys
        //       checkedKeys.splice(index, 1, item.key);
        //       this.selectListMap[item.id + item.attributes.deptId] = item;
        //     }
        //   });
        // }
        if (item.children) {
          this.dealTreeCheckedKeys(item.children, checkedKeys);
        }
      });
    },
    /*  tree 方法 start */

    // tree 自动初始化节点
    autoLoadAsyn() {
      this.loadDataAsyn(null);
    },
    // tree 请求数据
    loadDataAsyn(node) {
      const keyword = this.searchText;

      return new Promise((resolve) => {
        if ((node && node.children) || (node && node?.dataRef && node.dataRef.children)) {
          resolve();
          return;
        }
        if (node && !this.treeLoadedKeys.includes(node.key)) {
          this.treeLoadedKeys = [...this.treeLoadedKeys, node.key];
        }
        // 非查询条件下异步加载节点，修改treeParam传递的node的id
        if (node) {
          const { id } = node;
          this.beforeLoadData(node, id);
        } else {
          this.iniTreeUrl();
        }
        let param = {};
        if (!keyword || keyword === '') {
          this.treeParam.parameter.keyword = keyword;
          param = this.treeParam;
        } else {
          param = this.searchTreeParam;
        }
        if (param.url === '' || param.url == null || param.url === undefined) {
          return;
        }
        this.$emit('loading', true);
        request({
          url: param.url,
          data: param.parameter ? param.parameter : '',
          method: param.method
        })
          .then((res) => {
            if (res.success) {
              if (res.data.length > 0) {
                res.data.sort((abc, def) => abc.attributes.orderBy - def.attributes.orderBy);
                const list = processNodes(res.data);
                if (node) {
                  node.children = [...list];
                  if (node.dataRef) {
                    node.dataRef.children = [...list];
                  }
                  this.treeData = [...this.treeData];
                  // 设置当前节点及子节点的选中
                  if (node.checked || this.needCheckedKeys.includes(node.key)) {
                    const checkChildNode = list.filter((item) => item.attributes && item.attributes.nodeType === 'user');
                    this.setSelectUserList(checkChildNode);
                    this.$emit('changeSelectUser', this.selectUser);
                    this.setCheckData();
                  }
                } else {
                  // this.treeData = [...list];
                  this.setExpandedKeys(list); // 初始化展开节点
                }
                // 根据右侧的数据，设置默认选中
                // if (this.treeCheckedKeys.length > 0) {
                list.forEach((item) => {
                  if (this.selectListMap[item.id + item.attributes.deptId]) {
                    this.treeCheckedKeys.push(item.key);
                  }
                  // const itemKeyLength = item.key.length - 32;
                  // if (!this.treeCheckedKeys.includes(item.key)) {
                  //   this.treeCheckedKeys.forEach((tim, index) => {
                  //     const timKeyLength = tim.length - 32;
                  //     if (tim.substring(0, timKeyLength) === item.key.substring(0, itemKeyLength)) {
                  //       this.treeCheckedKeys.splice(index, 1, item.key);
                  //       this.selectListMap[item.key.substring(0, itemKeyLength) + item.attributes.deptId] = item;
                  //     }
                  //   });
                  // }
                });
                this.treeCheckedKeys = [...this.treeCheckedKeys];
                // }
                if ((node.checked || this.needCheckedKeys.includes(node.key)) && this.checkChildrenNode) {
                  // 递归选中子节点的子节点
                  setTimeout(() => {
                    this.checkNodes(list);
                    this.needCheckedKeys = this.needCheckedKeys.filter((item) => item !== node.key);
                  }, 0);
                }
              } else {
                node.isLeaf = true;
                node.dataRef.isLeaf = true;
                this.treeData = [...this.treeData];
                this.emptyText = '暂无数据！';
              }
            }
            // if(node.title == '产品开发组'){
            //   consoloe.log('node',node)
            // }
            this.$emit('loading', false);
            resolve(true);
          })
          .catch(() => {
            this.$emit('loading', false);
            resolve(true);
          });
      });
    },
    async checkNodes(childrens) {
      if (!childrens) return;
      const loadedKeys = [];
      childrens.forEach((node) => {
        if (!node.isLeaf && !this.treeLoadedKeys.includes(node.key)) {
          loadedKeys.push(node.key);
        }
      });
      if (loadedKeys.length > 0) {
        this.needCheckedKeys = [...this.needCheckedKeys, ...loadedKeys];
      }
      this.loadChildren(childrens).then(() => {
        const keys = childrens.map((item) => {
          if (!item.isLeaf) {
            return item.key;
          }
          return null;
        });
        this.expandedKeys = [...this.expandedKeys, ...keys];
        this.treeLoadedKeys = [...this.treeLoadedKeys, ...keys];
      });
    },
    // tree 选中操作 点击label 选中和取消
    selectTree(selectedKeys, { selected, node }) {
      if (selected && node.attributes.nodeType === 'user') {
        // 选中
        if (!this.treeCheckable) {
          this.selectListMap = {}; // 单选清空原来的数据
        }
        if (!this.selectListMap[node.id + node.attributes.deptId]) {
          this.selectListMap[node.id + node.attributes.deptId] = { ...node };
          this.selectUser.forEach((tim) => {
            if (tim.selectFlowTab === this.selectFlowTab) {
              tim.users = Object.values(this.selectListMap);
            }
          });
        }
      } else if (!selected && node.attributes.nodeType === 'user') {
        // 取消
        if (this.selectListMap[node.id + node.attributes.deptId]) {
          delete this.selectListMap[node.id + node.attributes.deptId];
        }
        // else if (this.selectListMap[node.id]) {
        //   delete this.selectListMap[node.id];
        // }
        this.selectUser.forEach((tim) => {
          if (tim.selectFlowTab === this.selectFlowTab) {
            tim.users = Object.values(this.selectListMap);
          }
        });
      }
      this.setCheckData();
      this.$emit('changeSelectUser', this.selectUser);
    },
    // step3. 复选框点击事件处理
    checkTree(checkedKeys, { checked, checkedNodes, node }) {
      // 多选
      /*
        1、勾选未加载子节点的节点时，通过改变展开节点先触发异步加载；
        2、(当前节点及子节点的)勾选效果在子节点加载完成后，根据当前节点的checked设置
      */
      if (!node.isLeaf && !this.treeLoadedKeys.includes(node.key)) {
        this.expandedKeys = [...this.expandedKeys, node.key];
        return;
      }
      // 根据当前节点的子节点选中状态区分当前操作为取消全选用户
      if (checked && !node.halfChecked && this.treeLoadedKeys.includes(node.key)) {
        // 递归当前节点的子节点选中状态
        let count = 0;
        const checkedNodeChildrenStatus = (list) => {
          if (!list) return;
          list.forEach((item) => {
            if (
              item.attributes &&
              item.attributes.nodeType === 'user' &&
              // !this.selectListMap[item.id] &&
              !this.selectListMap[item.id + item.attributes.deptId]
            ) {
              count = count + 1;
            }
            if (count === 0 && item.children && item.children.length > 0) {
              checkedNodeChildrenStatus(item.children);
            }
          });
        };
        if (this.checkChildrenNode) {
          this.checkNodes(node.children);
        }
        checkedNodeChildrenStatus(node.children);
        const unCheckedNodeCount = count;
        if (!unCheckedNodeCount) {
          this.deleteNode(node);
          this.setCheckData();
          return;
        }
      }
      if (!checked) {
        // 节点删除操作，先删除selectListMap中的节点信息
        this.deleteNode(node);
        this.selectUser.forEach((tim) => {
          if (tim.selectFlowTab === this.selectFlowTab) {
            tim.users = Object.values(this.selectListMap);
          }
        });
      } else {
        // 选中操作
        const select = checkedNodes;
        this.setSelectUserList(select);
      }
      this.$emit('changeSelectUser', this.selectUser);
    },
    onLoad(loadedKeys) {
      this.treeLoadedKeys = [...loadedKeys];
    },
    /*  tree 方法 end */
    // 删除节点
    deleteNode(node) {
      if (node.isLeaf) {
        if (this.selectListMap[node.id + node.attributes.deptId]) {
          delete this.selectListMap[node.id + node.attributes.deptId];
        }
        // else if (this.selectListMap[node.id]) {
        //   // 删除部门
        //   delete this.selectListMap[node.id + node.attributes.deptId];
        // }
      } else if (node.children && node.children.length > 0) {
        node.children.forEach((tim) => {
          this.deleteNode(tim);
        });
      } else if (node.dataRef.children && node.dataRef.children.length > 0) {
        node.dataRef.children.forEach((tim) => {
          this.deleteNode(tim);
        });
      }
    },
    // 过滤出选中的节点
    setSelectUserList(nodes) {
      const selectList = []; // 保存选中的节点
      if (nodes) {
        nodes.forEach((tim) => {
          // if (!this.selectListMap[tim.id] && tim.attributes.nodeType !='dept') {
          // 过滤用户user添加到右侧列表
          if (tim.attributes && tim.attributes.nodeType === 'user') {
            if (!this.selectListMap[tim.id + tim.attributes.deptId]) {
              const str = JSON.stringify(tim);
              const item = JSON.parse(str);
              selectList.push(item);
              this.selectListMap[tim.id + tim.attributes.deptId] = item;
            }
          }
        });
      }
      this.setDatatoSelectUser(selectList);
    },
    // 选中的节点放入selectUser 中
    setDatatoSelectUser(list) {
      this.selectUser.forEach((tim) => {
        if (tim.selectFlowTab === this.selectFlowTab) {
          // 暂时解决切换页签左侧值会出现重复的问题
          const ids = tim.users.map((item) => item.id);
          const arr = list.filter((node) => {
            if (!ids.includes(node.id)) {
              return true;
            }
            if (tim.users.some((user) => node.id === user.id && user.attributes.deptId !== node.attributes.deptId)) {
              return true;
            }
            return false;
          });
          tim.users = tim.users.concat(arr);
        }
      });
    },
    // 设置treeCheckedKeys
    setCheckData() {
      const keys = Object.values(this.selectListMap).map((item) => item.key);
      this.treeCheckedKeys = [...keys];
    },
    // 加载子节点数据
    loadChildren(list = []) {
      const nodes = list.filter((item) => !item.isLeaf);
      if (nodes.length > 0) {
        const promises = [];
        nodes.forEach((element) => {
          promises.push(this.loadDataAsyn(element));
        });
        return new Promise((resolve) => {
          Promise.all(promises).then(() => {
            resolve(true);
          });
        });
      }
      return new Promise((resolve) => {
        resolve(true);
      });
    },
    // 初始化展开节点操作
    async setExpandedKeys(list = []) {
      this.loadChildren(list).then(() => {
        const keys = list.map((item) => {
          if (!item.isLeaf) {
            return item.key;
          }
          return null;
        });
        this.expandedKeys = [...keys];
        this.treeData = [...list];
        this.loading = false;
      });
    },
    /**
     * 把平台返回的tree数据转换成 ant.design tree数据
     * @param {*} data  原始数据
     * @param {*} scopedSlot   可通过 slot-scope 属性支持的属性
     * @param {*} scopedSlot   可通过 slot-scope 属性支持的属性
     */
    // eslint-disable-next-line max-params
    processTreeData(data, nodeType, _scopedSlot, custom) {
      const result = [];
      if (data && data.length > 0) {
        data.forEach((tim) => {
          const tree = {
            id: tim.id,
            nodeType: tim.nodeType ? tim.nodeType : nodeType,
            title: tim.name,
            key: tim.id,
            isLeaf: false,
            _parentId: this.defaultMaxParentId,
            disableCheckbox: false,
            disabled: false,
            selectable: true
            // checked: false
          };
          if (custom) {
            custom(tree);
          }
          result.push(tree);
        });
      }
      return result;
    }
  }
};
</script>
